<?php

namespace App\Http\Controllers\User;

use App\Events\Invite;
use App\Events\Login;
use App\Events\Register;
use App\Http\Controllers\BaseController;
use App\Models\User;
use App\Rules\Code;
use EasyWeChat\Factory;
use Hashids\Hashids;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

class LoginController extends BaseController
{
    public function index(Request $request)
    {
        $param = $this->validate($request,[
            'phone' => 'size:11',
            'avatar' => 'string',
            'nickname' => 'string',
            'invite_code' => 'string|size:6',
            'platform' => 'required|in:app,min,pc',
            'auth' => 'in:wx,qq,phone',
            'wx_app_openid' => 'max:100',
            'qq_openid' => 'max:100',
            'wx_min_openid' => 'max:100',
            'code' => ['exclude_if:platform,min',new Code()]
        ]);


        $hashids = new Hashids('',6);
        if (isset($param['invitation_code'])){
            $param['parent_id'] = $hashids->decode($param['invitation_code'])[0];
        }


        switch ($param['platform']){
            case 'app':
                switch ($param['auth']){
                    case 'wx':
                        if (empty($param['wx_app_openid'])){
                            return  $this->error('微信openid不能为空');
                        }
                        $user = User::query()->where('wx_app_openid',$param['wx_app_openid'])->first();
                        if ($user){
                            $token = auth('api')->login($user);
                            event(new Login($user->getKey()));

                            return $this->success(['token' => 'Bearer '.$token]);
                        }
                        if (empty($param['phone'])){
                            return response()->json(['code' => 1000,'msg' => '缺少手机号']);
                        }
                        $user = User::query()->where('phone',$param['phone'])->first();
                        if ($user){
                            $user->wx_app_openid = $param['wx_app_openid'];
                            $user->save();
                        }else{
                            if (isset($param['invite_code'])){
                                $param['parent_id'] = $hashids->decode($param['invite_code'])[0];
                            }

                            $user = User::query()->create($param);
                            $user->invite_code = $hashids->encode($user->getKey());
                            $user->save();
                            event(new Register($user->getKey()));
                        }
                        event(new Login($user->getKey()));
                        $token = auth('api')->login($user);
                        return $this->success(['token' => 'Bearer '.$token]);
                    case 'qq' :
                        if (empty($param['qq_openid'])){
                            return  $this->error('qqopenid不能为空');
                        }
                        $user = User::query()->where('qq_openid',$param['qq_openid'])->first();
                        if ($user){
                            $token = auth('api')->login($user);
                            event(new Login($user->getKey()));
                            return $this->success(['token' => 'Bearer '.$token]);
                        }

                        if (empty($param['phone'])){
                            return response()->json(['code' => 1000,'msg' => '缺少手机号']);
                        }
                        $user = User::query()->where('phone',$param['phone'])->first();
                        if ($user){
                            $user->qq_openid = $param['qq_openid'];
                            $user->save();
                        }else{
                            if (isset($param['invite_code'])){
                                $param['parent_id'] = $hashids->decode($param['invite_code'])[0];
                                event(new Invite($user->getKey()));
                            }

                            $user = User::query()->create($param);
                            $user->invite_code = $hashids->encode($user->getKey());
                            $user->save();
                            event(new Register($user->getKey()));

                        }

                        event(new Login($user->getKey()));
                        $token = auth('api')->login($user);
                        return $this->success(['token' => 'Bearer '.$token]);

                    case 'phone' :
                        if (empty($param['phone'])){
                            return $this->error('手机号不能为空');
                        }
                        $user = User::query()->where('phone',$param['phone'])->first();
                        if (empty($user)){
                            if (isset($param['invite_code'])){
                                $param['parent_id'] = $hashids->decode($param['invite_code'])[0];

                            }
                            $user =  User::query()->create($param);
                            if (isset($param['parent_id'])){
                                event(new Invite($user->getKey()));
                            }
                            $user->invite_code = $hashids->encode($user->getKey());
                            $user->save();
                            event(new Register($user->getKey()));
                        }
                        event(new Login($user->getKey()));
                        $token = auth('api')->login($user);
                        return $this->success(['token' => 'Bearer '.$token]);
                }
                break;
            case 'min':
                if (empty($param['wx_min_openid'])){
                    return  $this->error('小程序openid不能为空');
                }
                $user = User::query()->where('wx_min_openid',$param['wx_min_openid'])->first();
                if ($user){
                    $token = auth('api')->login($user);
                    event(new Login($user->getKey()));
                    return $this->success(['token' => 'Bearer '.$token]);
                }

                if (empty($param['phone'])){
                    return response()->json(['code' => 1000,'msg' => '缺少手机号']);
                }

                $user = User::query()->where('phone',$param['phone'])->first();
                if ($user){
                    $user->wx_min_openid = $param['wx_min_openid'];
                    $user->save();
                }else{
                    if (isset($param['invite_code'])){
                        $param['parent_id'] = $hashids->decode($param['invite_code'])[0];
                        event(new Invite($user->getKey()));
                    }
                    $user = User::query()->create($param);
                    $user->invite_code = $hashids->encode($user->getKey());
                    $user->save();
                }
                event(new Login($user->getKey()));
                $token = auth('api')->login($user);
                return $this->success(['token' => 'Bearer '.$token]);
            case 'pc':

                break;
        }
    }



    // 获取小程程序手机号
    public function minPhone(Request $request)
    {
        $param = $this->validate($request,[
            'code' => 'required',
        ]);

        $app = Factory::miniProgram(config('min'));
        $result = $app->phone_number->getUserPhoneNumber($param['code']);
        if ($result['errcode']!=0){
            return  $this->error();
        }
        $phone  = $result['phone_info']['purePhoneNumber'];
        return $this->success(['phone' => $phone]);
    }

    // 获取小程程序openid
    public function minOpenid(Request $request)
    {
        $param = $this->validate($request,[
            'code' => 'required',
        ]);

        $app = Factory::miniProgram(config('min'));
        $res =  $app->auth->session($param['code']);
        return  $this->success($res);
    }


    // 获取app微信授权信息
    public function appUser(Request $request)
    {
        $param = $this->validate($request,[
            'code' => 'required'
        ]);

        $result =  Http::get('https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxa381a302dc72a610&secret=d0497c3651e230331518a806f8891f04&code='.$param['code'].'&grant_type=authorization_code')->json();
        if (isset($result['access_token'])){
            Cache::put('app_wx_token_info',$result['access_token'],7000);
            $userInfo =  Http::get('https://api.weixin.qq.com/sns/userinfo?access_token='.$result['access_token'].'&openid='.$result['openid'].'&lang=zh_CN')->json();
            return  $this->success($userInfo);
        }

       if (Cache::has('app_wx_token_info')) {
           $result = Cache::get('app_wx_access_token');
           $userInfo =  Http::get('https://api.weixin.qq.com/sns/userinfo?access_token='.$result['access_token'].'&openid='.$result['openid'].'&lang=zh_CN')->json();
           return  $this->success($userInfo);
       }else{
           $result =  Http::get('https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxa381a302dc72a610&secret=d0497c3651e230331518a806f8891f04&code='.$param['code'].'&grant_type=authorization_code')->json();
           if (isset($result['access_token'])){
               Cache::put('app_wx_token_info',$result['access_token'],7000);
               $userInfo =  Http::get('https://api.weixin.qq.com/sns/userinfo?access_token='.$result['access_token'].'&openid='.$result['openid'].'&lang=zh_CN')->json();
               return  $this->success($userInfo);
           }
       }

       return $this->error();
    }


    public function logout()
   {
        auth('api')->logout();
        return $this->success();
    }
}
